import T from 'ant-design-vue/es/table/Table'
import axios from '@/utils/ajaxRequest'

export default {
  data() {
    return {
      sOrderBy: this.orderBy,
      sFilter: this.filter,
      selectedRows: [],
      selectedRowKeys: [],

      localLoading: false, //是否显示加载
      localDataSource: [], //缓存数据
      localPagination: {} //缓存分页的配置
    }
  },
  props: Object.assign({}, T.props, {

    //分页器
    pageSize: {
      type: Number, //默认分页10条 
      default: 10
    },
    current: {
      type: Number, //默认查询第一页
      default: 1,
    },
    size: {
      type: String, //默认表格的尺寸
      default: "middle"
    },

    showQuickJumper: { //是否可以快速跳转
      type: Boolean,
      default: true,
    },
    showSizeChanger: { //是否展现切换分页数量
      type: Boolean,
      default: true,
    },
    pageSizeOptions: { //分页数量的配置
      type: Array,
      default: function () {
        return ["5", "10", "20", "30", "50"]
      }
    },
    showPagination: { // 是否展示分页
      type: String | Boolean,
      default: 'auto'
    },

    //表格
    bordered: { // 是否显示表格边框
      type: Boolean,
      default: false,
    },
    rowKey: {
      type: [String, Function],
      default: 'id'
    },
    columns: { // 表格的配置
      type: Array,
      default: () => []
    },

    request: { // 请求数据默认指向
      type: Object,
      default: () => {
        return {
          top: "$top",
          skip: "$skip",
          attributes: "$attributes",
          filter: "$filter",
          orderBy: "$orderBy",
          count: "$count"
        }
      }
    },
    response: { // 请求返回默认的指向
      type: Object,
      default: () => {
        return {
          data: "data",
          count: "count"
        }
      }
    },
    beforeload: { // beforeload
      type: Function,
      default: null
    },

    total: { //总共多少
      type: Number,
      dafault: 0
    },
    //查询 
    searchUrl: { //查询的URL
      type: String,
      default: ""
    },
    method: { // 查询方式
      type: String,
      default: 'get'
    },

    count: {
      type: Boolean,
      default: true
    },
    orderBy: { //排序
      type: Array,
      default: () => [
        ["id", "desc"]
      ]
    },
    filter: { //查询条件
      type: String,
      default: ""
    },
    attributes: {// 查询字段
      type: String,
      default: ""
    },
  }),


  computed: {
    // 计算查询排序
    searchOrderBy() {
      return this.sOrderBy.map(item => {
        return item.join(" ")
      }).join(",")
    },
    searchFilter() {
      return this.sFilter
    }
  },
  watch: {
    pageSize(val) {
      Object.assign(this.localPagination, {
        pageSize: val
      })
    },
    current(val) {
      Object.assign(this.localPagination, {
        current: val
      })
    }
  },

  created() {
    //当前页 生成分页器

    const localPageNum = this.current;
    const localPageSizeOptions = this.pageSizeOptions
    this.localPagination = ['auto', true].includes(this.showPagination) && Object.assign({}, this.localPagination, {
      current: localPageNum,
      pageSize: this.pageSize,
      showQuickJumper: this.showQuickJumper,
      pageSizeOptions: localPageSizeOptions,
      showSizeChanger: this.showSizeChanger,
      showTotal: this.showTotal,
      size: this.size,
    }) || false

    this.loadData()


  },
  methods: {

    //显示共多少条
    showTotal(total) {
      return `共 ${total} 条`
    },
    /**
       * 表格重新加载方法
       * 如果参数为 true, 则强制刷新到第一页
       * @param current bool
       */
    refresh(current) {
      if (current) {
        this.localPagination.current = 1;
      }
      this.loadData()
    },

    // 清楚filter
    resetFilter() {
      this.localPagination.filter = null;
    },
    /**
     * 加载数据方法
     * @param {Object} pagination 分页选项器
     * @param {Object} filter 过滤条件
     * @param {Object} sorter 排序条件
     */
    loadData(pagination, filter, sorter) {

      //显示加载 
      this.localLoading = true
      //搜索条件
      if(!sorter){ //搜索条件不变

      }else if(sorter.field){ //搜索条件变更
        this.sOrderBy = [[sorter.field, sorter.order == "descend" ? "desc" : "asc"]]
      }else{ //搜索条件重置
        this.sOrderBy = this.orderBy 
      }

      let parameter = {
        [this.request.orderBy]: this.searchOrderBy,
        [this.request.count]: this.count
      };
      if (this.showPagination) { //分页
        pagination = pagination || this.localPagination;
        parameter[this.request.skip] = (pagination.current - 1) * pagination.pageSize;
        parameter[this.request.top] = pagination.pageSize;
      }
      if (this.searchFilter) { //过滤条件
        parameter[this.request.filter] = this.searchFilter;
      }
      if (this.attributes) { //过滤条件
        parameter[this.request.attributes] = this.attributes
      }

      //这里判断是不是 自己传的查询条件 如果是 从第一页查起
      if (Object.prototype.toString.call(filter) == "[object String]" || filter === "") {
        this.sFilter = filter;

        parameter[this.request.skip] = 0
        parameter[this.request.filter] = this.searchFilter

        pagination = {
          current: 1,
          pageSize: pagination ? pagination.pageSize : null
        }
      }

      axios.request({
        url: this.searchUrl,
        method: this.method,
        params: parameter
      }).then(data => {
        //beforeload
        if (this.beforeload) {
          data = this.beforeload(data);
        }
        if (this.showPagination) {
          this.localPagination = Object.assign({}, this.localPagination, {
            current: pagination.current,
            pageSize: pagination.pageSize,
            showSizeChanger: this.showSizeChanger,  
            total: data[this.response.count], // 返回结果中的总记录数 
          })
        } else {
          this.localPagination = false
        }
        // // 为防止删除数据后导致页面当前页面数据长度为 0 ,自动翻页到上一页
        // if ((pagination && pagination.current) && data[this.response.data].length === 0 && this.showPagination && this.localPagination.current > 1) {
        //   this.localPagination.current--
        //   this.loadData()
        //   return
        // }
        // 这里用于判断接口是否有返回 r.totalCount 且 this.showPagination = true 且 pageNo 和 pageSize 存在 且 totalCount 小于等于 pageNo * pageSize 的大小
        // 当情况满足时，表示数据不满足分页大小，关闭 table 分页功能
        // try {
        //   if (((this.count && this.showPagination) && data[this.response.count] <= (this.localPagination.current * this.localPagination.pageSize))) {
        //     this.localPagination.hideOnSinglePage = true
        //   }
        // } catch (e) {
        //   this.localPagination = false
        // }
        this.localDataSource = this.count ? data[this.response.data] : data
        this.localLoading = false
      }).catch(() => {
        this.localLoading = false
      })
    }

  },
  render() {
    const props = {}
    Object.keys(T.props).forEach(k => {
      this[k] && (props[k] = this[k])
      return props[k]
    })
    
    props.pagination = this.localPagination
    props.loading = this.localLoading
    props.dataSource = this.localDataSource
    // console.log(props.pagination)
    const table = (
      <a-table {...{ props, scopedSlots: { ...this.$scopedSlots } }} onChange={this.loadData}>
        {Object.keys(this.$slots).map(name => (<template slot={name}>{this.$slots[name]}</template>))}
      </a-table>
    )
    return (<div class="table-wrapper">
      {table}
    </div>)
  }
}